<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>WebSocket-Demo</title>
</head>
<body>
<input type="text" id="text"/>
<button onclick="send()">发送消息</button>
<button onclick="closeConn()">关闭连接</button>
<input type="text" id="answer" name="test1">
<div id="msg"></div>
</body>
<script>
    if (!"WebSocket" in window) {
        alert("Not Support WebSocket");
    }
    const clientId = Math.random().toString().substring(2);

    const websocket = new WebSocket("ws://localhost:8080/ws/" +
        clientId);

    websocket.onerror = function () {
        setMessageInnerHTML("error");
    };
    websocket.onopen = function () {
        setMessageInnerHTML("connect success");
    };
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    };
    websocket.onclose = function () {
        setMessageInnerHTML("close");
    };

    websocket.onbeforeunload = function () {
        websocket.close();
    };

    const setMessageInnerHTML = (innerHtml) => {

        var answerInput = document.getElementById("answer");
        // answerInput.setAttribute("value", innerHtml);
        answerInput.value=innerHtml
        document.getElementById("msg").innerHTML += innerHtml + "<br>";
    };
    const send = () => {
        websocket.send(document.getElementById("text").value);
        document.getElementById("text").value = "";
    };
    const closeConn = () => {
        websocket.close();
    };

</script>
</html>

